package com.module.frame.retrofit

import com.google.gson.GsonBuilder
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.net.Proxy
import java.security.SecureRandom
import java.security.cert.CertificateException
import java.security.cert.X509Certificate
import java.util.concurrent.TimeUnit
import javax.net.ssl.*

var baseUrl = ""

abstract class BaseFrameRetrofit : IExtendInterceptors {
    lateinit var client: OkHttpClient
    var retrofit: Retrofit? = null
    var debug: Boolean = true

    //扩展的拦截器列表
    protected var mInterceptorList: List<Interceptor> = ArrayList()

    /**
     * 初始化
     */
    fun init(url: String, debug: Boolean) {
        this@BaseFrameRetrofit.debug = debug
        baseUrl = url
        //可以设置请求过滤的水平,body,basic,headers
        val interceptorList = provideCustomInterceptors()
        val mBuilder = OkHttpClient.Builder()
        //添加扩展拦截器
        if (interceptorList.isNotEmpty()) {
            for (mInterceptor in interceptorList) {
                mBuilder.addInterceptor(mInterceptor)
            }
        }

        //okhttp 配置
        mBuilder //不加以下两行代码,https请求不到自签名的服务器
            .hostnameVerifier(TrustAllHostnameVerifier()) //校验名称,这个对象就是信任所有的主机,也就是信任所有https的请求
            .connectTimeout(30, TimeUnit.SECONDS) //连接超时时间
            .readTimeout(30, TimeUnit.SECONDS) //读取超时时间
            .writeTimeout(30, TimeUnit.SECONDS) //写入超时时间
            .retryOnConnectionFailure(false) //连接不上是否重连,false不重连
        if (!debug) {
            //线上版本不代理
            mBuilder.proxy(Proxy.NO_PROXY)
        }

        createSSLSocketFactory()?.let { mBuilder.sslSocketFactory(it, TrustAllCerts()) } //创建一个证书对象
        client = mBuilder.build()


        // 获取retrofit的实例
        retrofit = Retrofit.Builder()
            .baseUrl(baseUrl)
            .addConverterFactory(GsonConverterFactory.create(GsonBuilder().create()))
//            .addCallAdapterFactory(Rxjava2CallAdapterFactories.create())//Rxjava2适配器
            .client(client)
            .build();


    }

    /**
     * 获取接口服务
     */
    fun <T> getService(serviceClass: Class<T>): T {
        val t = if (retrofit != null) {
            retrofit?.create(serviceClass)!!
        } else {
            init(baseUrl, debug)
            retrofit?.create(serviceClass)!!
        }
        return t;
    }


    /**
     * 实现https请求
     */
    private fun createSSLSocketFactory(): SSLSocketFactory? {
        var ssfFactory: SSLSocketFactory? = null
        try {
            val sc = SSLContext.getInstance("TLS")
            sc.init(null, arrayOf<TrustManager>(TrustAllCerts()), SecureRandom())
            ssfFactory = sc.socketFactory
        } catch (e: Exception) {
        }
        return ssfFactory
    }

    inner class TrustAllCerts : X509TrustManager {
        @Throws(CertificateException::class)
        override fun checkClientTrusted(p0: Array<out X509Certificate>?, p1: String?) {
        }

        @Throws(CertificateException::class)
        override fun checkServerTrusted(p0: Array<out X509Certificate>?, p1: String?) {
        }

        override fun getAcceptedIssuers(): Array<X509Certificate?> {
            return arrayOfNulls(0)
        }

    }

    /**
     * 信任所有的服务器,返回true
     */
    inner class TrustAllHostnameVerifier : HostnameVerifier {
        override fun verify(hostname: String, session: SSLSession): Boolean {
            return true
        }
    }
}
